﻿using System;
using System.Collections.Generic;
using System.Text;

namespace HZY.EFCore
{
    using HZY.EFCore.Interface;
    using Microsoft.EntityFrameworkCore;
    using System.Threading.Tasks;

    public class HZYUnitOfWorkBase<TDbContext> : IUnitOfWork
        where TDbContext : DbContext
    {
        public HZYUnitOfWorkBase(TDbContext _Context)
        {
            this.Context = _Context;
        }

        public virtual TDbContext Context { get; set; }

        protected bool IsCommit { get; set; } = false;

        public virtual DbSet<T> Set<T>()
            where T : class
            => this.Context.Set<T>();

        #region 异步方法

        public virtual async Task<int> SaveAsync()
        {
            if (this.IsCommit)
            {
                return 0;
            }
            return await this.Context.SaveChangesAsync();
        }

        public virtual async Task<bool> CommitAsync(Action Call)
        {
            try
            {
                this.IsCommit = true;

                Call?.Invoke();

                this.IsCommit = false;

                return await this.Context.SaveChangesAsync() > 0;
            }
            catch (Exception e)
            {
                throw;
            }

            //using (var transaction = this.Context.Database.BeginTransaction())
            //{
            //    try
            //    {
            //        Call?.Invoke();
            //        await transaction.CommitAsync();
            //        return true;
            //    }
            //    catch (Exception e)
            //    {
            //        if (transaction != null) await transaction.RollbackAsync();
            //        throw;
            //    }
            //}
        }

        #endregion

        #region 同步方法

        public virtual int Save()
        {
            if (this.IsCommit)
            {
                return 0;
            }
            return this.Context.SaveChanges();
        }

        public virtual bool Commit(Action Call)
        {
            try
            {
                this.IsCommit = true;

                Call?.Invoke();

                this.IsCommit = false;

                return this.Context.SaveChanges() > 0;
            }
            catch (Exception e)
            {
                throw;
            }
        }

        #endregion




    }
}
